//
//  BuildSelectController.m
//  QRMaster
//
//  Created by myApple on 16/6/1.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "BuildSelectController.h"
#import "AllocateBulidingModel.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "validateInputValue.h"
#import "SetStaffBuildTimeCell.h"
#import "AllocateRoomProcess.h"

@interface BuildSelectController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * buildTabelView;
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton * backBtn;
    NSMutableArray * selectBuildId;
    AllocateRoomProcess * dataProcess;
}
@end

@implementation BuildSelectController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom ;
        selectBuildId = [[NSMutableArray alloc]init];
        dataProcess = [[AllocateRoomProcess alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareNavBtn];
    [self prepareTabelView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setAllocateBuildArray:(NSMutableArray *)allocateBuildArray
{
    _allocateBuildArray = allocateBuildArray;
    selectBuildId = [allocateBuildArray mutableCopy];
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makeSureChoose)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(userBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

#pragma mark --------------tableview
-(void)prepareTabelView
{
    float x = 0;
    float y = 5;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64 - y;
    
    buildTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    buildTabelView.dataSource = self;
    buildTabelView.delegate = self;
    buildTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:buildTabelView];
}

#pragma mark ---------tableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _buildDisplayArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AssignBuildTimeModel * model = _buildDisplayArray[indexPath.row];
    SetStaffBuildTimeCell * cell = [SetStaffBuildTimeCell cellWithTableView:tableView];
    cell.accessoryType = UITableViewCellAccessoryNone;
    [cell setData:model];
    for (NSString * roomId in selectBuildId) {
        if ([roomId isEqualToString:model.buildingid]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AssignBuildTimeModel * model = _buildDisplayArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [selectBuildId removeObject:model.buildingid];
    }
    else
    {
        [selectBuildId addObject:model.buildingid];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    [self judgeSelect];
}

#pragma mark -----------确定选择
-(void)makeSureChoose
{
    NSString *paramStr=@"";
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSMutableString * roomString = [[NSMutableString alloc]init];
    NSArray * allRoomArray = [dataProcess getAllRoomIdOfBuildId:selectBuildId withBuildArray:_buildingArray];
    for (NSString * roomId in allRoomArray) {
        [roomString appendString:roomId];
        [roomString appendString:@","];
    }
    if(roomString.length > 0)
    {
        NSRange range;
        range.location = roomString.length - 1;
        range.length = 1;
        [roomString deleteCharactersInRange:range];
    }
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    if ([_guestOrStaff isEqualToString:@"1"]) {
        [postDict setValue:_memeberID forKey:@"userId"];
        [postDict setValue:roomString forKey:@"roomStr"];
        paramStr = POST(ADDSTAFFROOM);
    }
    else if([_guestOrStaff isEqualToString:@"0"])
    {
        [postDict setValue:_memeberID forKey:@"userId"];
        [postDict setValue:roomString forKey:@"roomStr"];
        paramStr = POST(ADDCLIENTROOMPOWER);
    }
    else
    {
        [postDict setValue:_groupId forKey:@"groupId"];
        [postDict setValue:_email forKey:@"email"];
        [postDict setValue:_mobile forKey:@"mobile"];
        if (_mobile != nil && ![_mobile isEqualToString:@""] && [validateInputValue isPureNumandCharacters:_mobile]) {
            [postDict setValue:_areaCode forKey:@"areaCode"];
        }
        [postDict setValue:roomString forKey:@"groupRoom"];
        
        paramStr = POST(EDITGROUPCLIENTROOM);
    }
    __block BuildSelectController * weakSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [self startWaiting:nil color:nil addToView:self.view];
    [rnw initWithPath:paramStr params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         NSArray * data = [downLoadData objectForKey:@"data"];
         if (data) {
             [PromptInfoView showMessage:NSLocalizedString(@"modifySuccess", nil) superView:weakSelf.view];
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
         }
         
     }
     ];
}

#pragma mark ----------用户自定义返回键
-(void)userBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSureChoose];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(BOOL)judgeSelect
{
    if (![dataProcess arrayItemIsSame:selectBuildId withArray:_allocateBuildArray]) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGB(0x7dc234);
        return YES;
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
        return NO;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
